package dao

import (
	"haiqiu-go-admin/entity"
	"haiqiu-go-admin/entity/dto"
	"haiqiu-go-admin/utils"
	"log"
	"strconv"
)

func MenuListByUserName(username string) (*[]entity.SysPermission, error) {
	rows, err := DB.Query("SELECT sp.id,"+
		"sp.parent_id,"+
		"COALESCE ( sp.title, '' ) AS title,"+
		"COALESCE ( sp.value, '' ) AS `value`,"+
		"sp.icon,"+
		"sp.path,"+
		"sp.active,"+
		"COALESCE ( sp.desc, '' ) AS `desc`,"+
		"COALESCE ( sp.method, '' ) AS `method`,"+
		"COALESCE ( sp.sort, 0 ) AS `sort`,"+
		"COALESCE ( sp.component, '' ) AS `component`,"+
		"type,"+
		"COALESCE ( sp.is_frame, 0 ) AS is_frame,"+
		"COALESCE ( sp.is_cache, 0 ) AS is_cache"+
		"    from sys_permission sp"+
		"    INNER JOIN sys_role_permission srp ON srp.permission_id = sp.id"+
		"    INNER JOIN sys_user_role sur ON sur.role_id = srp.role_id"+
		"    INNER JOIN sys_user su ON su.id = sur.user_id"+
		"    WHERE 1=1 and sp.active != 0 and sp.`type` != 2 and su.username = ?"+
		"    order by sp.sort", username)
	if err != nil {
		return nil, err
	}
	var sysPermissions []entity.SysPermission
	for rows.Next() {
		var sysPermission entity.SysPermission
		err := rows.Scan(
			&sysPermission.Id,
			&sysPermission.ParentId,
			&sysPermission.Title,
			&sysPermission.Value,
			&sysPermission.Icon,
			&sysPermission.Path,
			&sysPermission.Active,
			&sysPermission.Desc,
			&sysPermission.Method,
			&sysPermission.Sort,
			&sysPermission.Component,
			&sysPermission.Type,
			&sysPermission.IsFrame,
			&sysPermission.IsCache,
		)
		if err != nil {
			return nil, err
		}
		sysPermissions = append(sysPermissions, sysPermission)
	}
	return &sysPermissions, nil
}

func MenuList(menuQueryDto *dto.MenuQueryParams) ([]entity.SysPermission, error) {
	columns := "id," +
		"parent_id," +
		"COALESCE ( title, '' ) AS title," +
		"COALESCE ( `VALUE`, '' ) AS `value`," +
		"icon," +
		"path," +
		"active," +
		"COALESCE ( `DESC`, '' ) AS `desc`," +
		"COALESCE ( method, '' ) AS `method`," +
		"COALESCE ( sort, 0 ) AS `sort`," +
		"COALESCE ( component, '' ) AS `component`," +
		"type," +
		"COALESCE ( is_frame, 0 ) AS is_frame," +
		"COALESCE ( is_cache, 0 ) AS is_cache," +
		"create_time," +
		"update_time "
	wrapper := utils.QueryWrapper().List("sys_permission", columns).OrderByDesc("sort")
	if menuQueryDto.Title != nil {
		wrapper.Like("title", *menuQueryDto.Title)
	}
	if menuQueryDto.Active != nil {
		wrapper.Eq("active", *menuQueryDto.Active)
	}
	rows, err := DB.Query(wrapper.GetSql(), wrapper.GetVal()...)
	if err != nil {
		log.Println(err.Error())
		return nil, err
	}
	sysPermissions := make([]entity.SysPermission, 0)
	for rows.Next() {
		var sysPermission entity.SysPermission
		err := rows.Scan(
			&sysPermission.Id,
			&sysPermission.ParentId,
			&sysPermission.Title,
			&sysPermission.Value,
			&sysPermission.Icon,
			&sysPermission.Path,
			&sysPermission.Active,
			&sysPermission.Desc,
			&sysPermission.Method,
			&sysPermission.Sort,
			&sysPermission.Component,
			&sysPermission.Type,
			&sysPermission.IsFrame,
			&sysPermission.IsCache,
			&sysPermission.CreateTime,
			&sysPermission.UpdateTime,
		)
		if err != nil {
			log.Println(err.Error())
			return nil, err
		}
		sysPermissions = append(sysPermissions, sysPermission)
	}
	return sysPermissions, nil
}

// MenuById 根据ID查询数据
func MenuById(id int64) (*entity.SysPermission, error) {
	row := DB.QueryRow("select "+
		"id,"+
		"parent_id,"+
		"COALESCE ( title, '' ) AS title,"+
		"COALESCE ( `VALUE`, '' ) AS `value`,"+
		"icon,"+
		"path,"+
		"active,"+
		"COALESCE ( `DESC`, '' ) AS `desc`,"+
		"COALESCE ( method, '' ) AS `method`,"+
		"COALESCE ( sort, 0 ) AS `sort`,"+
		"COALESCE ( component, '' ) AS `component`,"+
		"type,"+
		"COALESCE ( is_frame, 0 ) AS is_frame,"+
		"COALESCE ( is_cache, 0 ) AS is_cache,"+
		"create_time,"+
		"update_time "+
		" from sys_permission where id = ?", id)
	var sysPermission entity.SysPermission
	err := row.Scan(
		&sysPermission.Id,
		&sysPermission.ParentId,
		&sysPermission.Title,
		&sysPermission.Value,
		&sysPermission.Icon,
		&sysPermission.Path,
		&sysPermission.Active,
		&sysPermission.Desc,
		&sysPermission.Method,
		&sysPermission.Sort,
		&sysPermission.Component,
		&sysPermission.Type,
		&sysPermission.IsFrame,
		&sysPermission.IsCache,
		&sysPermission.CreateTime,
		&sysPermission.UpdateTime,
	)
	if err != nil {
		panic(err)
	}
	return &sysPermission, nil
}

// MenuPageCount 分页查询总条数
func MenuPageCount() (count int64) {
	err := DB.QueryRow("select count(1) from sys_permission").Scan(&count)
	if err != nil {
		log.Println(err.Error())
	}
	return count
}

// MenuPageList 分页查询数据
func MenuPageList(page, pageSize int64) (*[]entity.SysPermission, error) {
	rows, err := DB.Query("select * from sys_permission limit ?,?", page, pageSize)
	if err != nil {
		log.Println(err.Error())
		return nil, err
	}
	var SysPermissions []entity.SysPermission
	for rows.Next() {
		var sysPermission = entity.SysPermission{}
		err := rows.Scan(
			&sysPermission.Id,
			&sysPermission.ParentId,
			&sysPermission.Title,
			&sysPermission.Value,
			&sysPermission.Icon,
			&sysPermission.Path,
			&sysPermission.Active,
			&sysPermission.Desc,
			&sysPermission.Method,
			&sysPermission.Sort,
			&sysPermission.Component,
			&sysPermission.Type,
			&sysPermission.IsFrame,
			&sysPermission.IsCache,
			&sysPermission.CreateTime,
			&sysPermission.UpdateTime,
		)
		if err != nil {
			log.Println(err.Error())
			return nil, err
		}
		SysPermissions = append(SysPermissions, sysPermission)
	}
	return &SysPermissions, nil
}

// MenuAdd 新增数据
func MenuAdd(sysPermission *entity.SysPermission) (int64, error) {
	exec, err := DB.Exec("INSERT INTO `sys_permission` "+
		"(`parent_id`, `title`, `value`, `icon`, `path`, `active`, "+
		"`desc`, `method`, `sort`, `component`,  `type`, `is_frame`,  `is_cache`, "+
		"`create_time`, `update_time`) VALUES "+
		"("+
		"?,?,?,?,?,"+
		"?,?,?,?,?,"+
		"?,?,?,?,? "+
		");",
		&sysPermission.ParentId,
		&sysPermission.Title,
		&sysPermission.Value,
		&sysPermission.Icon,
		&sysPermission.Path,
		&sysPermission.Active,
		&sysPermission.Desc,
		&sysPermission.Method,
		&sysPermission.Sort,
		&sysPermission.Component,
		&sysPermission.Type,
		&sysPermission.IsFrame,
		&sysPermission.IsCache,
		&sysPermission.CreateTime,
		&sysPermission.UpdateTime,
	)
	if err != nil {
		panic(err)
		return 0, err
	}
	rowsAffected, err := exec.RowsAffected()
	if err != nil {
		panic(err)
		return 0, err
	}
	return rowsAffected, nil
}

// MenuUpdate 根据ID更新数据
func MenuUpdate(sysPermission *entity.SysPermission) (int64, error) {
	exec, err := DB.Exec("UPDATE `sys_permission` set "+
		"`parent_id`=? , `title`=? , `value`=? , `icon`=? , `path`=? , `active`=? , "+
		"`desc`=? , `method`=? , `sort`=? , `component`=? ,  `type`=? , `is_frame`=? ,  `is_cache`=? , "+
		"`create_time`=? , `update_time`=? where id = ?",
		&sysPermission.ParentId,
		&sysPermission.Title,
		&sysPermission.Value,
		&sysPermission.Icon,
		&sysPermission.Path,
		&sysPermission.Active,
		&sysPermission.Desc,
		&sysPermission.Method,
		&sysPermission.Sort,
		&sysPermission.Component,
		&sysPermission.Type,
		&sysPermission.IsFrame,
		&sysPermission.IsCache,
		&sysPermission.CreateTime,
		&sysPermission.UpdateTime,
		&sysPermission.Id,
	)
	if err != nil {
		return 0, err
	}
	rowsAffected, err := exec.RowsAffected()
	if err != nil {
		return 0, err
	}
	return rowsAffected, nil
}

// MenuDelete 根据ID删除数据
func MenuDelete(id int64) (int64, error) {
	exec, err := DB.Exec("delete from sys_permission where id = ?")
	if err != nil {
		panic(err)
		return 0, err
	}
	rowsAffected, err := exec.RowsAffected()
	if err != nil {
		panic(err)
		return 0, err
	}
	return rowsAffected, nil
}

// MenuDeleteBatch 根据ID批量删除数据
func MenuDeleteBatch(ids []int64) (int64, error) {
	var idsStr string
	for index, id := range ids {
		if index == len(ids)-1 {
			idsStr += strconv.FormatInt(id, 10)
		} else {
			idsStr += strconv.FormatInt(id, 10) + ", "
		}
	}
	exec, err := DB.Exec("delete from sys_permission where id in (?)", idsStr)
	if err != nil {
		panic(err)
		return 0, err
	}
	rowsAffected, err := exec.RowsAffected()
	if err != nil {
		panic(err)
		return 0, err
	}
	return rowsAffected, nil
}

func MenuByRoleId(roleId int64) (*[]entity.SysPermission, error) {
	rows, err := DB.Query("SELECT sp.id, sp.parent_id, sp.`title` "+
		"FROM sys_role_permission srp "+
		"INNER JOIN sys_permission sp ON srp.permission_id = sp.id "+
		"WHERE srp.role_id = ?", roleId)
	if err != nil {
		log.Println(err.Error())
		return nil, err
	}
	var SysPermissions []entity.SysPermission
	for rows.Next() {
		var sysPermission = entity.SysPermission{}
		err := rows.Scan(
			&sysPermission.Id,
			&sysPermission.ParentId,
			&sysPermission.Title,
		)
		if err != nil {
			log.Println(err.Error())
			return nil, err
		}
		SysPermissions = append(SysPermissions, sysPermission)
	}
	return &SysPermissions, nil
}
